package com.dodoke.framework.security.wechat.service;

import com.dodoke.common.core.domain.entity.SysWechatUserDO;
import com.dodoke.common.core.domain.model.LoginUser;
import com.dodoke.common.exception.CustomException;
import com.dodoke.common.utils.StringUtils;
import com.dodoke.framework.web.service.SysPermissionService;
import com.dodoke.system.service.ISysWechatUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 短信验证码登陆用户验证处理
 */
@Service("wechatUserDetailsService")
public class WechatUserDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(WechatUserDetailsServiceImpl.class);

    @Autowired
    private ISysWechatUserService sysWechatUserService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String openId) throws UsernameNotFoundException {

        SysWechatUserDO user = sysWechatUserService.selectSysWechatUserByOpenId(openId);

        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在." , openId);
            throw new CustomException("微信小程序登录用户：" + openId + " 不存在");
        }

        // 创建 Spring Security UserDetails 用户明细
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysWechatUserDO user) {
        return new LoginUser(user, permissionService.getMenuPermission(user));
    }
}
